package com.sql.azarias.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sql.azarias.AppManager;
import com.sql.azarias.http.AbstractRequestNew;
import com.sql.azarias.http.CallServer;
import com.sql.azarias.http.HttpListener;

import butterknife.ButterKnife;

/**
 * Created by ShangQiangLong on 2017/3/1.
 */

public abstract class BaseMvpFragment<V,T extends BasePresenter<V>> extends Fragment {
    public T presenter;
    protected Context mActivity;
    public boolean isVisible;
    public boolean isFirst=true;
    public boolean isPrepared;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //绑定View
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        initInjector();


        presenter = initPresenter();
        //activity创建完成 控件全部找到
        isPrepared=true;
        //初始化数据(一般指调用网络请求方法)
        lazyLoad();

        presenter.attach((V)this);
        return view;
    }


    protected <T> void request(Context activity, AbstractRequestNew<T> request, HttpListener<T> httpListener ) {
        CallServer.getInstance().add(activity,0, request, httpListener);
    }

    protected <T> void request(Context activity , int what, AbstractRequestNew<T> request, HttpListener<T> httpListener) {
        CallServer.getInstance().add(activity,what, request, httpListener);
    }
    @Override
    public void onAttach(Context context) {
        this.mActivity = context;
        super.onAttach(context);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.dettach();
    }
    //这个方法用来缓加载首页的fragment http://www.cnblogs.com/xjx22/p/5424630.html
    //如果没有viewpager+fragment  单纯点击跳转fragment 就判断栈中有没有fragemnt 有的话显示show没有隐藏hide
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //视图可见
        if(getUserVisibleHint()){
            isVisible=true;
            lazyLoad();
        }else{
            isVisible=false;
        }

    }

    public void lazyLoad(){

        if(!isVisible||!isPrepared||!isFirst){
            return;
        }
        initEventAndData();
        isFirst=false;
    }
    public abstract T initPresenter();
    protected abstract int getLayoutId();

    protected abstract void initInjector();

    protected abstract void initEventAndData();
}
